package com.mayflygeek.mayflyask.controller;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mayflygeek.mayflyask.entity.User;
import com.mayflygeek.mayflyask.service.SendEmailService;
import com.mayflygeek.mayflyask.service.UserService;

/**
 * @author 蝈蝈 
 * @email guodefu909@126.com
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * 重置密码Controller
 */
@Controller
@RequestMapping(value = "/resetPassword")
public class ResetPasswordController {

	
	private Logger log = LoggerFactory.getLogger(getClass());

	@Resource
	private UserService userService;
	
	@Resource
	private SendEmailService sendEmailService;
	
//	进入重置密码页
	@RequestMapping(value = "/toResetPassword")
	public String toResetPassword() {
		log.info("toResetPassword");
		return "resetPasswordStepOne";
	}
	
//	重置密码第一步，输入验证邮箱
	@RequestMapping(value = "/stepOne")
	public String resetPasswordStepOne(String userName,ModelMap model) {
		User userResult = userService.getByUserName(userName);
		String resetPasswordUrl = "http://localhost:8080/mayflyask"+"/resetPassword/confirm?userName="+userResult.getUserName()+"&salt="+userResult.getSalt();
		sendEmailService.sendResetPasswordEmail(userName, resetPasswordUrl);
		model.addAttribute("userName", userName);
		return "resetPasswordStepOneResult";
	}
	
//	邮箱确认，进入重置密码第二步
	@RequestMapping(value = "/confirm")
	public String resetPasswordConfirm(String userName, String salt, ModelMap model) {
		User userResult = userService.getByUserName(userName);
		if (userResult != null && userResult.getSalt().equals(salt)) {
			model.addAttribute("userName",userName);
			return "resetPasswordStepTwo";
		}
		model.addAttribute("message","链接无效！");
		return "forward:/login/toLogin";
	}
	
//	重置密码第二步，设置新密码
	@RequestMapping(value = "/stepTwo")
	public String resetPasswordStepTwo(User user,ModelMap model) {
		if (user != null && user.getUserName()!=null && user.getPassword()!=null && user.getPassword().equals(user.getConfirmPassword())) {
			User userResult = userService.getByUserName(user.getUserName());
			if (userResult !=null && userResult.getStatus()==1) {
				userResult.setPassword(user.getPassword());
				userService.updateUser(userResult);
				return "resetPasswordStepTwoResult";
			}
		}
		model.addAttribute("message","重置密码出错！");
		return "forward:/login/toLogin";
	}
}
